import json
from langchain_core.messages import AIMessage,HumanMessage
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_openai import OpenAI
from langgraph.graph import END,START,StateGraph,MessagesState
from langgraph.store.memory import BaseStore,InMemoryStore

model = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key="sk-965dc39b016c49ecbe29de180f4db2b6", # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
recommendation_prompt = ChatPromptTemplate.from_messages([

])
recommendation_chain = recommendation_prompt | model | (lambda x: {"messages":[AIMessage(content=x.content)]})

def recommend_products(state:MessagesState,config:RunnableConfig,store:InMemoryStore):
    """根据用户存储的偏好推荐产品"""
    user_id = config['configurable']['user_id']
    namespace = ("user_profiles",user_id)
    user_profile_record = store.get(namespace,"profile")
    user_profile = user_profile_record.value if user_profile_record else {}
    user_profile_summary = format_user_profile_summary(user_profile)
    result = recommendation_chain.invoke({"user_profile_summary":user_profile_summary})
    return result

def format_user_profile_summary(user_profile:dict) -> str:
    """将用户资料字典格式还为字符串进行提示注入"""
    name = user_profile.get("preferred_name","用户")